<!DOCTYPE html>
<!--
Copyright (c) 2013 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<link rel="import" href="/tracing/base/utils.html">
<link rel="import" href="/tracing/ui/analysis/object_instance_view.html">
<link rel="import" href="/tracing/ui/analysis/object_snapshot_view.html">
<link rel="import" href="/tracing/ui/base/ui.html">
<link rel="import" href="/tracing/ui/tracks/multi_row_track.html">
<link rel="import" href="/tracing/ui/tracks/object_instance_track.html">

<script>
'use strict';

tr.exportTo('tr.ui.tracks', function() {
  /**
   * A track that displays a ObjectInstanceGroup.
   * @constructor
   * @extends {ContainerTrack}
   */
  const ObjectInstanceGroupTrack = tr.ui.b.define(
      'object-instance-group-track', tr.ui.tracks.MultiRowTrack);

  ObjectInstanceGroupTrack.prototype = {

    __proto__: tr.ui.tracks.MultiRowTrack.prototype,

    decorate(viewport) {
      tr.ui.tracks.MultiRowTrack.prototype.decorate.call(this, viewport);
      Polymer.dom(this).classList.add('object-instance-group-track');
      this.objectInstances_ = undefined;
    },

    get objectInstances() {
      return this.itemsToGroup;
    },

    set objectInstances(objectInstances) {
      this.setItemsToGroup(objectInstances);
    },

    addSubTrack_(objectInstances) {
      const hasMultipleRows = this.subRows.length > 1;
      const track = new tr.ui.tracks.ObjectInstanceTrack(this.viewport);
      track.objectInstances = objectInstances;
      Polymer.dom(this).appendChild(track);
      return track;
    },

    buildSubRows_(objectInstances) {
      objectInstances.sort(function(x, y) {
        return x.creationTs - y.creationTs;
      });

      const subRows = [];
      for (let i = 0; i < objectInstances.length; i++) {
        const objectInstance = objectInstances[i];

        let found = false;
        for (let j = 0; j < subRows.length; j++) {
          const subRow = subRows[j];
          const lastItemInSubRow = subRow[subRow.length - 1];
          if (objectInstance.creationTs >= lastItemInSubRow.deletionTs) {
            found = true;
            subRow.push(objectInstance);
            break;
          }
        }
        if (!found) {
          subRows.push([objectInstance]);
        }
      }
      return subRows;
    },
    updateHeadingAndTooltip_() {
    }
  };

  return {
    ObjectInstanceGroupTrack,
  };
});
</script>
